<?php
namespace backend\modules\mobo\controllers;

use Yii;
//use backend\modules\mobo\models\BackendMenu;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use backend\base\BaseBackendController;

use \backend\modules\mobo\models\Models;
use \backend\modules\mobo\models\ModelsField;
use common\components\Tree;
use base\YiiMobo;

class ModelsController extends BaseBackendController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
    //项目中改为renderPartial渲染，所以layout无效
	//public $layout='//layouts/column2'; 
    public $categorys;
	
	public $type = 'content';
	
	public $uid;
	
	public $model;
	
	public $modelid;
	
	public $models;
	
	public $fields;
	
	public $models_table;
	
	public $models_field_table;
	
	
	public $modelstype;
	
	
	
	public function init(){
		parent::init();
	    $this->uid = 'xiong';
		$this->models_table = Models::tableName();
		$this->models_field_table = ModelsField::tableName();
		$this->type = isset($_REQUEST['type']) && $_REQUEST['type'] ? $_REQUEST['type'] : 'content';
		
		$this->modelstype = array(
		    'content'=> '内容模型',
			'category'=> '分类模型',
			'user'=> '会员模型',
		);
	}
	/**
	 * @return array action filters
	 */
	public function filters() {
     return array( 
        array('auth.filters.AuthFilter'),
            );
        }


    public function CreateField($model){
		//echo $model->type;
		//exit;
		$model_path = Yii::getAlias('@mobo')."/views/models/sql/model_$model->type.sql";
		$sql = file_get_contents($model_path);

		
		$sql = str_replace('{{%$table}}', '{{%'.$model->tablename.'}}', $sql);
		$sql = str_replace('{{%models_field}}',$this->models_field_table, $sql);
		$sql = str_replace('{{%$modelid}}',$model->modelid, $sql);
		//echo $sql;
		//exit;
		
		//if ($model->type == 'content'){
		$sql = str_replace('{{%$table_data}}', '{{%'.$model->tablename.'_data}}', $sql);
		$sql = str_replace(PHP_EOL, '', $sql);
		    
		//}
		
		Yii::$app->db->createCommand($sql)->execute();
		//exit;
	}
	
	
	public function actionCheckTablename($modelid = '', $tablename){
		$sql="SHOW TABLES LIKE '{{{%$tablename}}}'";
		$result = Yii::$app->db->createCommand($sql)->queryAll();
		//print_r($result);
		echo ($result==null || $modelid!='') ? 'true' : 'false';
	}
	/**
	 * 添加数据内容.
     * 添加数据库内容的表单提交处理
	 * 模板文件通常为  views/category/_form.php
	 */
	public function actionCreate()
	{
		$model = self::findModel();
        if($model->load(Yii::$app->request->post()))
		{
			if($model->save()){
				self::actionUpdateCache($model->modelid);
				self::CreateField($model);
				$this->OperTips($this->createUrl(['mobo/models/index', 'type'=>$model->type]));
			}
		}
		$model->type = $this->type;
		return $this->render('models_form',array(
			'model'=>$model,
			'modelstype'=>$this->modelstype,
		));
	}

	/**
	 * 更新数据内容
	 * 模板文件通常为  views/category/_form.php
	 * @param $id 一般为数据库表的主键值
	 */
	public function actionUpdate($modelid)
	{
		$this->modelid = $modelid;
		$model= self::findModel($modelid);
		if(isset($_POST['Models']))
		{
			$model->attributes=$_POST['Models'];
			$model->setting = $model->setting ? json_encode($model->setting) : '';
			if($model->save()){
				$this->actionUpdateCache($modelid);
				$this->OperTips($this->createUrl(['mobo/models/index', 'type'=>$model->type]));
			}
		}
        
		$this->models = Yii::$app->FileCache->get('backend_models_'.$modelid);
		$models['fields'] = $this->models['fields'];
		$models['models'] = $this->models['models'];
		$model->setting = $model->setting ? json_decode($model->setting, true) : array();
		return $this->render('models_form',array(
			'model'=>$model,
			'models' => $models,
			'fields'=> self::listorderFields(),
			'type'=>$this->type,
			'modelstype'=>$this->modelstype,
		));
	}
	
	


	/**
	 * 删除某一条数据
	 * 一般来自控制器的默认方法index
	 * @param $id 一般为数据库表的主键值
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}
    
    /**
	 * 批量操作（删除）一些记录
	 * 一般来自控制器的默认方法index
	 * @param $id 一般为数据库表的主键值
	 */
	public function actionBatch()
	{
        $ids = isset($_POST['checked_catid']) ? $_POST['checked_catid'] : NULL;
        if ($ids){
            if (isset($_POST['batch_delete'])){
                Category::model()->deleteByPk($ids); 
                //$backurl = $_SERVER['HTTP_REFERER'];
                $backurl = $this->createUrl('index');  //跳转到控制器index方法
				$this->renderPartial('//_return/jump',array(
					'backurl'=>$backurl,
					'type'=> '',
				));
                exit();
            }
        }
	}

	/**
	 * 显示数据内容
     * 改变了默认的方法，读取数据、传递参数、分页更为自由
     * 模板文件默认为 views/category/index.php
	 */
	public function actionIndex(){

		$sql="SELECT * FROM `$this->models_table` where `type` = '$this->type'";
		if (isset($_POST['keyword'])){
			$sql .= " and (title like '%".$_POST['keyword']."%')";
		}
		$sql .= " order by modelid desc";

        return $this->render('models_index', array_merge(YiiMobo::pageRows($sql), ['type'=>$this->type]));
	}

	/**
	 * 显示数据内容
     * 改变了默认的方法，读取数据、传递参数、分页更为自由
     * 模板文件默认为 views/category/index.php
	 */
	public function actionField($modelid){

		$sql="SELECT * FROM $this->models_field_table where modelid = $modelid";
		$sql .= " order by listorder asc,fieldid asc";
		return $this->render('models_field', array_merge(YiiMobo::pageRows($sql), ['modelid'=>$modelid]));
		
	}
	
    /**
	 * 批量操作（删除）一些记录
	 * 一般来自控制器的默认方法index
	 * @param $id 一般为数据库表的主键值
	 */
	public function actionFieldBatch(){
        $ids = isset($_POST['checked_fieldid']) ? $_POST['checked_fieldid'] : NULL;
		$tips = '';
		$backurl = $_SERVER['HTTP_REFERER'];
        if ($ids){
            if (isset($_POST['batch_delete'])){
                BackendModelsField::model()->deleteByPk($ids);
                $tips = Yii::$app->params['batch_delete'];
            }
			
        }else if(isset($_POST['batch_listorder'])){
			if ($_POST['listorder']) foreach($_POST['listorder'] as $id=>$listorder){
				
				 BackendModelsField::model()->updateAll(array('listorder'=>intval($listorder)), 'fieldid='.$id);
			}
			$tips = Yii::$app->params['batch_listorder'];
		}
        $this->actionUpdateCache($_POST['modelid']);
		$this->jumpPage($backurl);
		exit();
	}
	
	//数据库添加字段
	public function alterField($modelid, $models){
		$sql="SELECT * FROM $this->models_table where modelid = $modelid";
		$model= Yii::$app->db->createCommand($sql)->queryOne();
		$tablename = $models->primarytable ? $model['tablename'] : $model['tablename'].'_data';
		$models->setting = json_decode($models->setting, true);
	    $sql = "alter table {{%$tablename}} add `$models->field` $models->fieldtype";
		$sql .= $models->fieldlength ? "($models->fieldlength)" : "";
		$sql .= $models->setting['defaultvalue'] ? " default '".$models->setting['defaultvalue']."'" : ""; 
		$aa = " not Null";
		Yii::$app->db->createCommand($sql)->execute();
	}
	/**
	 * 新建字段
	 */
	public function actionCreateField($modelid = '', $fieldid = ''){
		$model = self::ModelsField($fieldid);
		if(isset($_POST['Field'])){
			
			$model->attributes=$_POST['Field'];
			$model->setting = json_encode($model->setting);
			$model->param = json_encode($model->param);
			if($model->save()){
				self::actionUpdateCache($model->modelid);
				self::alterField($model->modelid, $model);
				$backurl = $this->createUrl(['mobo/models/field', 'modelid'=> $model->modelid]);
				$this->OperTips($backurl);
			}
		}
		
		$formtype = $model->formtype;
		$param = json_decode($model->param, true);

		return $this->render('models_field_form',array(
			'model'=>$model,
			'modelid'=> $modelid
			
		));
	}
	/**
	 * 修改字段
	 * 
	 */
	public function actionUpdateField($modelid = '', $fieldid){
		$model = self::ModelsField($fieldid);
		
		if(isset($_POST['Field'])){
			$model->attributes=$_POST['Field'];
			$model->setting = $model->setting ? json_encode($model->setting) : '';

			$model->param = $model->param ? json_encode($model->param) : '';
			if($model->save()){
				self::actionUpdateCache($model->modelid);
				$backurl = $this->createUrl('Field', array('modelid'=> $_POST['Field']['modelid']));
				$this->jumpPage($backurl);
			}
		}
		
		$formtype = $model->formtype;
		
        $model->setting = $model->setting ? json_decode($model->setting, true) : array();
		$model->param = $model->param ? json_decode($model->param, true) : array();   
		return $this->render('models_field_form',array(
			'model'=>$model,
			'modelid'=> $modelid,
			'param' => self::actionFormfield($formtype, $model->param, true)
		));
	}
	
	
	
	
	/**
	* 更新栏目缓存
	*
	*
	*/
	public function actionUpdateCache($modelid){
		$tablename = $this->models_table;
		$sql="SELECT * FROM $tablename where modelid = $modelid";
		$data['models'] = Yii::$app->db->createCommand($sql)->queryOne();
		
        $data['models']['setting'] = $data['models']['setting'] ? json_decode($data['models']['setting'] ,true) : array();
		$data['models']['param'] = $data['models']['param'] ? json_decode($data['models']['param'] ,true) : array();
		$sql="SELECT * FROM $this->models_field_table where modelid = $modelid order by listorder asc, fieldid desc";
		$data['fields'] = Yii::$app->db->createCommand($sql)->queryAll();
		
		$fields = array();
		$savefunction = array();
		
		foreach($data['fields'] as $k=>$v){
		    $v['setting'] = $v['setting'] ? json_decode($v['setting'] ,true) : array();
			$v['param'] = $v['param'] ? json_decode($v['param'] ,true) : array();
			$fields[$v['fieldid']] = $v;
			if (isset($v['param']['savefunction']) && $v['param']['savefunction']){
				$savefunction[$v['field']] = $v['param']['savefunction'];
			}
		}
		$data['fields'] = $fields;
		Yii::$app->FileCache->set('backend_models_'.$modelid, $data);
		$tablename = $data['models']['tablename'];
		$function = "<?php".PHP_EOL.PHP_EOL;
		$function .= "class save_{$tablename}{".PHP_EOL.PHP_EOL;
		$function .= "public \$data;".PHP_EOL;
		$function .= "public \$modelid;".PHP_EOL.PHP_EOL;
        $function .= "function __construct(\$data, \$modelid) {".PHP_EOL;
		$function .= "\$this->modelid = \$modelid;".PHP_EOL;
		$function .= "\$this->data = \$data;".PHP_EOL;
        $function .= "}".PHP_EOL.PHP_EOL;
		foreach($savefunction as $k=>$v){
			if ($v){
				$function .= '    public function '.$k.'($data){'.PHP_EOL;
				$function .= '        $value = $data[\''.$k.'\'];'.PHP_EOL;
				$function .= '        '.$v.PHP_EOL;
				
				$function .= '    }'.PHP_EOL.PHP_EOL;
			}
			
		}
		$function .= '}'.PHP_EOL;;
		$sFile = "../runtime/cache/models/save_{$tablename}.php";
		$handle = fopen($sFile,'wb');
		fwrite($handle, $function);
		fclose($handle);
		
        //echo $function;
		//exit;
		
	}
	
	
	public function actionFormfield($formtype, $param = array(), $return = false){
		$template = "@common/widgets/$formtype/views/_field";
		
		$data['form'] = $this->render($template,array(
			'formtype'=>$formtype,
			'param' => $param
		), true);
		if ($return){
		     return $data;
		}else{
			echo json_encode($data);
		}
		
	}
	

    public function listorderFields(){
		$fields = array();
		$this->models = Yii::$app->FileCache->get('backend_models_'.$this->modelid);
		$this->fields = $this->models['fields'];
		$this->models = $this->models['models'];
		//print_r($this->fields);
		//exit;
		
		$listorder = isset($this->models['setting']['index']['listorder']) ? $this->models['setting']['index']['listorder'] : array();
		//print_r($listorder);
		//exit;
	    foreach($this->fields as $k=>$v){
			//echo $k.',';
			if(!in_array($k, $listorder)) $fields[$k] = $v;
		}
			
		$fields = $listorder ? array_flip($listorder) + $fields : array_reverse($this->fields);
		return $fields;
	}
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Category the loaded model
	 * @throws CHttpException
	 */
    protected function findModel($id = '')
    {
		$model =$id ? Models::findOne($id) : new Models;
        if ( $model !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
	public function ModelsField($id = null)
	{
		$model = $id ? ModelsField::findOne($id) : new ModelsField();
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
	

	/**
	 * Performs the AJAX validation.
	 * @param Category $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='category-form')
		{
			echo CActiveForm::validate($model);
			Yii::$app->end();
		}
	}
}
